#!/bin/bash

# Flight策略Docker部署脚本
# 支持AI自动分配交易数量功能

set -e

echo "🚀 Flight策略Docker部署开始..."
echo "=================================="

# 检查必要文件
check_files() {
    echo "📋 检查必要文件..."
    
    required_files=(
        "docker-compose.yml"
        "Dockerfile"
        "requirements.txt"
        "accounts_config.json"
        ".env"
        "flight_strategy.py"
        "multi_account_manager.py"
    )
    
    for file in "${required_files[@]}"; do
        if [[ ! -f "$file" ]]; then
            echo "❌ 缺少必要文件: $file"
            exit 1
        fi
    done
    
    echo "✅ 所有必要文件存在"
}

# 检查环境变量
check_env_vars() {
    echo "🔧 检查环境变量..."
    
    # 检查.env文件
    if [[ ! -f ".env" ]]; then
        echo "❌ .env文件不存在"
        exit 1
    fi
    
    # 检查关键环境变量
    source .env
    
    required_vars=(
        "DEEPSEEK_API_KEY"
        "OKX_DEMO_API_KEY"
        "OKX_DEMO_SECRET"
        "OKX_DEMO_PASSWORD"
        "TELEGRAM_BOT_TOKEN"
    )
    
    missing_vars=()
    for var in "${required_vars[@]}"; do
        if [[ -z "${!var}" ]]; then
            missing_vars+=("$var")
        fi
    done
    
    if [[ ${#missing_vars[@]} -gt 0 ]]; then
        echo "❌ 缺少环境变量: ${missing_vars[*]}"
        exit 1
    fi
    
    echo "✅ 环境变量检查通过"
}

# 验证Flight策略配置
validate_flight_config() {
    echo "🎯 验证Flight策略配置..."
    
    # 检查accounts_config.json中的Flight策略配置
    if ! grep -q '"strategy": "flight"' accounts_config.json; then
        echo "❌ accounts_config.json中未找到Flight策略配置"
        exit 1
    fi
    
    # 检查是否移除了amount字段
    if grep -q '"amount"' accounts_config.json; then
        echo "⚠️ 警告: accounts_config.json中仍存在amount字段，AI自动分配功能可能无法正常工作"
    fi
    
    # 检查启用的账户
    enabled_accounts=$(grep -c '"enabled": true' accounts_config.json)
    if [[ $enabled_accounts -eq 0 ]]; then
        echo "❌ 没有启用的账户"
        exit 1
    fi
    
    echo "✅ Flight策略配置验证通过"
    echo "📊 启用的账户数量: $enabled_accounts"
}

# 测试Flight策略AI分配功能
test_flight_ai_allocation() {
    echo "🤖 测试Flight策略AI分配功能..."
    
    # 创建临时测试脚本
    cat > test_flight_docker.py << 'EOF'
import sys
import os
sys.path.append('/app')

try:
    from flight_strategy import calculate_flight_position_size
    
    # 测试AI分配功能
    test_result = calculate_flight_position_size(
        symbol='BTC/USDT:USDT',
        account_balance=1000,
        leverage=20,
        position_size_ratio=0.01,
        confidence='MEDIUM'
    )
    
    if test_result > 0:
        print(f"✅ Flight策略AI分配测试通过: {test_result}")
        sys.exit(0)
    else:
        print("❌ Flight策略AI分配测试失败")
        sys.exit(1)
        
except Exception as e:
    print(f"❌ Flight策略AI分配测试异常: {e}")
    sys.exit(1)
EOF
    
    # 在Docker容器中测试
    if docker run --rm \
        --env-file .env \
        -v $(pwd):/app \
        python:3.10-slim \
        bash -c "cd /app && pip install -q pandas numpy && python test_flight_docker.py"; then
        echo "✅ Flight策略AI分配功能正常"
    else
        echo "❌ Flight策略AI分配功能异常"
        rm -f test_flight_docker.py
        exit 1
    fi
    
    rm -f test_flight_docker.py
}

# 构建Docker镜像
build_images() {
    echo "🔨 构建Docker镜像..."
    
    # 构建主应用镜像
    docker-compose build --no-cache
    
    echo "✅ Docker镜像构建完成"
}

# 启动服务
start_services() {
    echo "🚀 启动Flight策略服务..."
    
    # 停止现有服务
    docker-compose down
    
    # 确保logs目录存在且有正确权限
    mkdir -p logs
    chmod 777 logs
    
    # 启动服务
    docker-compose up -d
    
    echo "✅ 服务启动完成"
}

# 验证服务状态
verify_services() {
    echo "🔍 验证服务状态..."
    
    # 等待服务启动
    sleep 10
    
    # 检查容器状态
    containers=("flight-trading-bot" "flight-monitor" "log-monitor")
    
    for container in "${containers[@]}"; do
        if docker ps --format "table {{.Names}}" | grep -q "$container"; then
            echo "✅ $container 运行正常"
        else
            echo "❌ $container 未运行"
            docker-compose logs "$container"
            exit 1
        fi
    done
    
    # 检查健康状态
    for container in "${containers[@]}"; do
        health=$(docker inspect --format='{{.State.Health.Status}}' "$container" 2>/dev/null || echo "none")
        if [[ "$health" == "healthy" || "$health" == "none" ]]; then
            echo "✅ $container 健康状态: $health"
        else
            echo "⚠️ $container 健康状态: $health"
        fi
    done
}

# 显示部署信息
show_deployment_info() {
    echo ""
    echo "🎉 Flight策略部署完成！"
    echo "=================================="
    echo ""
    echo "📊 服务状态:"
    docker-compose ps
    echo ""
    echo "📝 重要信息:"
    echo "  - Flight策略AI自动分配功能: ✅ 已启用"
    echo "  - 多账号管理: ✅ 运行中"
    echo "  - 日志监控: ✅ http://localhost:8080"
    echo "  - 配置文件: accounts_config.json"
    echo ""
    echo "🔧 管理命令:"
    echo "  查看日志: docker-compose logs -f flight-trading-bot"
    echo "  查看状态: docker-compose ps"
    echo "  重启服务: docker-compose restart"
    echo "  停止服务: docker-compose down"
    echo ""
    echo "📈 监控地址:"
    echo "  日志监控: http://localhost:8080"
    echo ""
    echo "⚠️  重要提醒:"
    echo "  - 确保环境变量正确配置"
    echo "  - 定期检查日志文件"
    echo "  - 监控Telegram通知"
    echo "  - AI会根据信心程度自动调整仓位大小"
}

# 主函数
main() {
    echo "Flight策略Docker部署脚本"
    echo "版本: 1.0"
    echo "功能: AI自动分配交易数量"
    echo ""
    
    # 执行部署步骤
    check_files
    check_env_vars
    validate_flight_config
    test_flight_ai_allocation
    build_images
    start_services
    verify_services
    show_deployment_info
    
    echo ""
    echo "🎯 部署成功！Flight策略AI自动分配功能已上线运行。"
}

# 错误处理
trap 'echo "❌ 部署过程中发生错误，请检查日志"; exit 1' ERR

# 执行主函数
main "$@"
